package com.cy.store.service.impl;

import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

/**
 * 用户模块业务层的实现类
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    HttpSession session;

    @Override
    public void reg(User user) {
        //调用mapper findByUsername(username)判断用户是否被注册过
        User result = userMapper.findByUsername(user.getUsername());

        //如果该用户名已经被注册过，抛出异常
        if (result != null) {
            throw new UsernameDuplicatedException("用户名被占用");
        }

        //密码md5加密
        // （串 + password + 串） -------md5加密
        //盐值 + password + 盐值 -------盐值是一个随机的字符串

        String oldPassword = user.getPassword();

        //获取盐值（随机生成一个盐值）
        String salt = UUID.randomUUID().toString().toUpperCase();

        //将密码和盐值作为一个整体加密处理
        String md5Password = getMD5Password(oldPassword, salt);

        //将加密之后的密码重新放置在user对象中
        user.setPassword(md5Password);

        //保存盐值
        user.setSalt(salt);

        // 补全数据：isdelete设置为0
        user.setIsDelete(0);

        // 补全数据：四个日志字段信息
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        user.setCreatedTime(new Date());
        user.setModifiedTime(new Date());

        //执行注册业务(rows == 1)
        Integer rows = userMapper.insert(user);
        if (rows == 0) {
            throw new InsertException("未知异常");
        }
    }

    @Override
    public User login(String username, String password) {
        //1.根据用户名称来查询用户数据是否存在，如果不存在抛出异常
        User result = userMapper.findByUsername(username);
        String salt = result.getSalt();
        String newPassowrd = getMD5Password(password, salt);
//        System.out.println(getMD5Password(password,result.getSalt()).equals(result.getPassword()));
        if (result == null) {
            throw new UserNotFoundException("用户名不存在");
        } else if (!(getMD5Password(password, result.getSalt()).equals(result.getPassword()))) {//将输入的密码进行md5加密后与数据库密码进行比对
            throw new PasswordNotMatchException("您的账号或密码输入有误");
        }
        //判断is_delete是否为1
        if (result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //重新封装对象，来提升系统的性能
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User user = userMapper.findByUid(uid);
        if (uid == null || user.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //将原始密码和输入的密码进行比较

        //如果密码不同，提示用户
        if (!(getMD5Password(oldPassword, user.getSalt()).equals(user.getPassword()))) {
            throw new PasswordNotMatchException("您输入的密码有误，请重新输入");
        }

        //进行修改
        newPassword = getMD5Password(newPassword, user.getSalt());
        Integer rows = userMapper.updatePasswordByUid(uid, newPassword, username, new Date());
        if (rows != 1) {
            throw new UpdateException("未知异常，请重新操作");
        }

    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //重新包装对象
        User user = new User();
        user.setUsername(result.getUsername());
        user.setEmail(result.getEmail());
        user.setPhone(result.getPhone());
        user.setGender(result.getGender());

        return user;
    }

    @Override
    public void changeInfo(Integer uid, String username, User user) {
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        user.setUid(uid);
//        user.setUsername(username);
        user.setModifiedTime(new Date());
        user.setModifiedUser(username);

        Integer rows = userMapper.updatInforByUid(user);
        if (rows != 1) {
            throw new UpdateException("未知异常");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        // 查询当前用户数据是否存在
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid, avatar, username, new Date());
        if (rows != 1) {
            throw new UpdateException("更新失败，请重新操作");
        }
    }

    /**
     * 第一一个md5算法加密
     */
    private String getMD5Password(String password, String salt) {

        for (int i = 0; i < 3; i++) {
            // md5加密算法调用(进行三次加密)
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toString();
        }
        //返回加密之后的password
        return password;
    }
}
